
package com.ruoyi.system.service.impl;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.domain.AttendanceRule;
import com.ruoyi.system.mapper.AttendanceRecordMapper;
import com.ruoyi.system.domain.AttendanceRecord;
import com.ruoyi.system.mapper.AttendanceRecordsMapper;
import com.ruoyi.system.mapper.AttendanceRuleMapper;
import com.ruoyi.system.service.IAttendanceRecordService;
import com.ruoyi.system.service.IAttendanceRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 考勤记录Service业务层处理
 */
@Service
public class AttendanceRecordServiceImpl implements IAttendanceRecordService {

    @Autowired
    private AttendanceRecordMapper attendanceRecordMapper;

    @Autowired
    private AttendanceRuleMapper attendanceRuleMapper;

    @Autowired
    private IAttendanceRuleService attendanceRuleService;

    // 上班打卡标准时间（9:00）
//    private static final int CHECK_IN_STANDARD_HOUR = 9;
    // 下班打卡标准时间（18:00）
//    private static final int CHECK_OUT_STANDARD_HOUR = 18;

    @Override
    public int handleCheckIn() {
        // 1. 获取当前用户ID
        Long userId = SecurityUtils.getUserId();

        // 2. 检查今天是否已打卡
        AttendanceRecord todayRecord = attendanceRecordMapper.selectTodayRecordByUserId(userId);
        if (todayRecord != null && todayRecord.getCheckInTime() != null) {
            throw new ServiceException("今日已打卡上班，请勿重复操作");
        }

        // 3. 获取当前用户的考勤规则
        AttendanceRule rule = attendanceRuleService.getRuleByUserId(userId);
        if (rule == null) {
            throw new ServiceException("未找到适用的考勤规则");
        }

        // 4. 检查当前时间是否早于打卡开始时间
        LocalTime nowTime = LocalDateTime.now().toLocalTime();
        LocalTime checkInStart = rule.getCheckInStart();
        if (nowTime.isBefore(checkInStart)) {
            throw new ServiceException("未到今天打卡时间，无法打卡");
        }

        // 5. 创建打卡记录（新记录或更新记录）
        AttendanceRecord record = todayRecord != null ? todayRecord : new AttendanceRecord();
        Date now = new Date();

        // 6. 设置打卡信息
        record.setUserId(userId);
        record.setCheckInTime(now);
        record.setCheckInMethod("MANUAL");
        record.setWorkDate(now);

        // 6. 判断打卡状态
//        Calendar cal = Calendar.getInstance();
//        cal.setTime(now);
//        cal.set(Calendar.HOUR_OF_DAY, CHECK_IN_STANDARD_HOUR);
//        cal.set(Calendar.MINUTE, 0);
//        cal.set(Calendar.SECOND, 0);
//        if (now.after(cal.getTime())) {
//            record.setStatus("LATE"); // 迟到
//        } else {
//            record.setStatus("NORMAL"); // 正常
//        }
        LocalTime checkInEnd = rule.getCheckInEnd();
        LocalTime lateThreshold = rule.getLateThreshold();

        if (nowTime.isAfter(checkInEnd)) {
            record.setStatus("ABSENT"); // 缺勤
        } else if (nowTime.isAfter(lateThreshold)) {
            record.setStatus("LATE"); // 迟到
        } else {
            record.setStatus("NORMAL"); // 正常
        }


        // 7. 保存记录
        if (todayRecord == null) {
            return attendanceRecordMapper.insertAttendanceRecord(record);
        } else {
            return attendanceRecordMapper.updateAttendanceRecord(record);
        }
    }

    @Override
    public int handleCheckOut() {
        // 1. 获取当前用户ID
        Long userId = SecurityUtils.getUserId();

        // 2. 查询今日打卡记录
        AttendanceRecord todayRecord = attendanceRecordMapper.selectTodayRecordByUserId(userId);
        if (todayRecord == null) {
            throw new ServiceException("请先完成上班打卡");
        }

        // 3. 检查是否已下班打卡
        if (todayRecord.getCheckOutTime() != null) {
            throw new ServiceException("今日已打卡下班，请勿重复操作");
        }

        // 4. 获取当前用户的考勤规则
        AttendanceRule rule = attendanceRuleService.getRuleByUserId(userId);
        if (rule == null) {
            throw new ServiceException("未找到适用的考勤规则");
        }

        // 5. 设置下班打卡信息
        Date now = new Date();
        todayRecord.setCheckOutTime(now);
        todayRecord.setCheckOutMethod("MANUAL");

        // 6. 检查是否早退
//        Calendar cal = Calendar.getInstance();
//        cal.setTime(now);
//        cal.set(Calendar.HOUR_OF_DAY, CHECK_OUT_STANDARD_HOUR);
//        cal.set(Calendar.MINUTE, 0);
//        cal.set(Calendar.SECOND, 0);
//
//        if (now.before(cal.getTime())) {
//            if (!"LATE".equals(todayRecord.getStatus())) {
//                todayRecord.setStatus("EARLY_LEAVE"); // 早退
//            }
//            // 如果既迟到又早退，保持迟到状态
//        }

        LocalTime nowTime = LocalDateTime.now().toLocalTime();
        LocalTime checkOutStart = rule.getCheckOutStart();
        LocalTime earlyLeaveThreshold = rule.getEarlyLeaveThreshold();

        if (nowTime.isBefore(checkOutStart)) {
            todayRecord.setStatus("EARLY_LEAVE"); // 早退
        } else {
            // 如果上班打卡正常，下班打卡正常才算正常
            if ("NORMAL".equals(todayRecord.getStatus())) {
                todayRecord.setStatus("NORMAL");
            } else {
                todayRecord.setStatus("ABSENT"); // 缺勤
            }
        }

        // 7. 更新记录
        return attendanceRecordMapper.updateAttendanceRecord(todayRecord);
    }

    @Override
    public AttendanceRecord selectTodayRecordByUserId(Long userId) {
        return attendanceRecordMapper.selectTodayRecordByUserId(userId);
    }

    // 以下是原有方法的实现保持不变...
    @Override
    public AttendanceRecord selectAttendanceRecordById(Long id) {
        return attendanceRecordMapper.selectAttendanceRecordById(id);
    }

    @Override
    public List<AttendanceRecord> selectAttendanceRecordList(AttendanceRecord attendanceRecord) {
        return attendanceRecordMapper.selectAttendanceRecordList(attendanceRecord);
    }

    @Override
    public int insertAttendanceRecord(AttendanceRecord attendanceRecord) {
        return attendanceRecordMapper.insertAttendanceRecord(attendanceRecord);
    }

    @Override
    public int updateAttendanceRecord(AttendanceRecord attendanceRecord) {
        return attendanceRecordMapper.updateAttendanceRecord(attendanceRecord);
    }

    @Override
    public int deleteAttendanceRecordByIds(Long[] ids) {
        return attendanceRecordMapper.deleteAttendanceRecordByIds(ids);
    }

    @Override
    public int deleteAttendanceRecordById(Long id) {
        return attendanceRecordMapper.deleteAttendanceRecordById(id);
    }

    @Override
    public int getContinuousNormalCheckInDays(Long userId) {
        List<Date> workDates = attendanceRecordMapper.selectNormalWorkDatesByUserId(userId);
        if (workDates == null || workDates.isEmpty()) {
            return 0;
        }

        // 转换为LocalDate并按倒序排序（最近日期在前）
        List<LocalDate> localDates = workDates.stream()
                .map(date -> date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
                .sorted(Comparator.reverseOrder())
                .collect(Collectors.toList());

        int continuousDays = 1; // 至少有1天正常打卡
        LocalDate lastDate = localDates.get(0); // 最近的正常打卡日期

        for (int i = 1; i < localDates.size(); i++) {
            LocalDate currentDate = localDates.get(i);
            // 检查是否是前一天（连续）
            if (currentDate.equals(lastDate.minusDays(1))) {
                continuousDays++;
                lastDate = currentDate; // 更新最近日期
            } else {
                break; // 不连续则停止计算
            }
        }
        return continuousDays;
    }


    @Override
    public List<Map<String, Object>> selectUsersWithNormalDaysLastMonth() {
        return attendanceRecordMapper.selectUsersWithNormalDaysLastMonth();
    }

}